<?php

namespace app\api\controller;

use app\api\middleware\Auth as MiddlewareAuth;
use app\common\BaseApiController;

class Auth extends BaseApiController
{
    protected $middleware = [
        MiddlewareAuth::class => [
            'except' => ['login', "logout"]
        ]
    ];

    public function login()
    {
        // 获取请求参数
        $data = $this->request->post();

        // 验证用户名和密码是否为空
        $validate = new \app\validate\Auth();
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 验证用户名和密码是否正确
        $user = \app\model\User::where('username', $data['username'])->find();

        if (!$user) {
            return json(['code' => 400, 'msg' => '账号密码错误']);
        }

        // 验证密码是否正确
        $result = password_verify($data['password'], $user['password']);

        if (!$result) {
            return json(['code' => 400, 'msg' => '账号密码错误']);
        }

        // 登录成功，生成token
        $token = \app\common\Token::createToken(['uid' => $user['id']]);
        return json(['code' => 200, 'msg' => '登录成功', 'data' => ['token' => $token]]);
    }

    public function logout()
    {
        return json(['code' => 200, 'msg' => '退出成功']);
    }
}
